package com.family.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.family.common.result.ResultCodeEnum;
import com.family.model.system.SysUser;
import com.family.system.custom.CustomUser;
import com.family.system.exception.GuiguException;
import com.family.system.mapper.SysUserMapper;
import com.family.system.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * @ClassName UserDetailsServiceImpl
 * @Date 2023-05-13 11:07
 * @AUTHOR family
 **/
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));

        if (null == sysUser) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        if (sysUser.getStatus() == 0) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }
        List<String> permsList = sysMenuService.findUserPermsList(sysUser.getId());
        sysUser.setUserPermsList(permsList);
        return new CustomUser(sysUser, Collections.emptyList());
    }
}
